﻿using Microsoft.AspNetCore.Http;
using StarsAdmin.Application.OperationLog.Dtos;
using StarsAdmin.Core.Extensions;
using System.Diagnostics;

namespace StarsAdmin.Web.Core.Middleware
{
    public class RequestLogMiddleware
    {
        private readonly RequestDelegate _next;

        public RequestLogMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task InvokeAsync(HttpContext context)
        {
            // 获取 HttpContext 和 HttpRequest 对象
            var request = context.Request;
            if (request.Path.Value != null && request.Path.Value.Contains("Login"))
            {
                await _next(context);
                await Task.CompletedTask;
            }
            // 创建一个计时器
            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();
            await _next(context);
            stopwatch.Stop();

            AddOperationLogInput logInput = new AddOperationLogInput()
            {
                Ip = context.GetRequestIPv4(),
                HttpMethod = request.Method,
                ApiPath = request.Path,
                ElapsedMilliseconds = stopwatch.ElapsedMilliseconds,
            };
        }
    }
}